<template>
  <button class="InputFile" type="button" :style="`font-size: ${size}px!important;`">
    <div>{{ text }}</div>
    <form :action="action" method="post" enctype="contentType">
      <input type="file" @change="handleUpload" ref="uploadFile" />
    </form>
  </button>
</template>

<script>
import { ref } from "vue";
import { ElNotification, ElLoading } from "element-plus"

export default {
  name: "kfileinput",
  props: ["modelValue", "type", "size", "text", "action", "contentType"],
  emits: ["update:modelValue"],
  setup(props, ctx) {
    let type = "*";
    let text = "upload"
    let uploadFile = ref("");
    let action = ""
    let contentType = "multipart/form-data"
    let size = 18;
    if (props.type) type = props.type;
    if (props.size) size = props.size;
    if (props.text) text = props.text;
    if (props.action) action = props.action;
    if (props.contentType) contentType = props.contentType;


    // 默认的文件类型


    function handleUpload(e) {
      let files = e.target.files;
      if (files.length > 0) {
        let file = files[0];
        if (typeReg[type].test(file.name)) {
          let reader = new FileReader();
          reader.onload = function (file_event) {
            ctx.emit("update:modelValue", {
              content : file_event.target.result,
              name : file.name
            });
          };
          reader.readAsBinaryString(file)
          // reader.readAsText(file)
        }
        else {
            ElNotification({
                title : "上载文件类型不对哦",
                message : "你应该上传的文件类型和后缀名为: " + typeCaption[type]
            })
        }
      }
      uploadFile.value = "";
    }

    return {
      handleUpload,
      uploadFile,
      size,
      text,
      action,
      contentType
    };
  },
};
</script>

<style scoped>
.InputFile {
  position: relative;
  display: inline-block;
  padding: 4px 12px;
  overflow: hidden;
  color: var(--mainColor);
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
  cursor: pointer;
  transition: all 0.3s linear;
  -moz-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
}
.InputFile input {
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}

.InputFile:hover {
  background: var(--mainColor);
  border-color: var(--mainColor);
  box-shadow: 0 0 15px var(--shadowColor), 0 0 15px var(--shadowColor),
    0 0 15px var(--shadowColor), 0 0 15px var(--shadowColor);
  color: white;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s linear;
  -moz-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
}
</style>
